import React from 'react';
import { Modal, Form, Input, message } from 'antd';

import { FormInstance } from 'antd/lib/form';
import { TTSInfo } from '../../../../schema/TTS';
import { createTTS, modifyTTS } from '../../../../servers/servers';
import { verifyNull } from 'utils/tools';
const { TextArea } = Input;

/**
 * TTS厂商props
 */
interface IProps {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

/**
 * TTS厂商state
 */
interface IState {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出弹窗的可见性
  visible: boolean;
}

/**
 * TTS厂商管理操作
 */
export class TTSPop extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的TTS厂商信息
  private TTSInfo?: TTSInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
    };
  }

  /**
   * 展开弹窗并设置类型
   */
  public open(mode: 'create' | 'modify'): void {
    this.setState({
      visible: true,
      mode: mode,
    });
  }

  /**
   * 关闭弹窗
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: TTSInfo) {
    setTimeout(() => {
      this.TTSInfo = val;
      this.formRef.current?.setFieldsValue(val);
    }, 0);
  }

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as TTSInfo;
      if (this.state.mode === 'create') {
        createTTS(val)
          .then(res => {
            if (res.code === 0) {
              message.success('创建成功');
              this.close();
              this.props.callback();
            } else {
              message.error(`${res.tips}(错误码:${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        const ttsManufacturerId = this.TTSInfo?.ttsManufacturerId as number;
        modifyTTS(ttsManufacturerId, val)
          .then(res => {
            if (res.code === 0) {
              message.success('修改成功');
              this.close();
              this.props.callback(ttsManufacturerId);
            } else {
              message.error(`${res.tips}(错误码:${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  render() {
    const { visible, mode } = this.state;

    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };

    return (
      <>
        <Modal
          title={mode === 'create' ? '新建TTS厂商' : '编辑TTS厂商'}
          width={500}
          visible={visible}
          onOk={() => {
            this.submitData();
          }}
          onCancel={() => {
            this.close();
          }}
        >
          <Form {...layout} layout="horizontal" ref={this.formRef}>
            <Form.Item
              label="TTS厂商名称"
              name="ttsManufacturerName"
              rules={verifyNull('请输入TTS厂商名称')}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input placeholder="请输入TTS厂商名称" maxLength={30} />
            </Form.Item>
            <Form.Item
              label="唯一标识"
              name="ttsManufacturerIdentifier"
              rules={verifyNull('请输入唯一标识')}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <TextArea rows={4} placeholder="请输入唯一标识" maxLength={250} />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}
